package com.duguyuan.client;

import com.duguyuan.utils.MessageProtocol;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;

public class ClientFrame extends JFrame {

    private static final int CLIENT_WIDTH = 1000;
    private static final int CLIENT_HEIGHT = 790;
    private static final int HEIGHT_CONTROLLER = 200;

    private static final Font TEXT_FONT = new Font("黑体", Font.PLAIN, 16);
    private static final Font LABEL_FONT = new Font("黑体", Font.BOLD, 18);
    private static final Font TEXTFIELD_FONT = new Font("黑体", Font.BOLD, 16);
    private static final Font BUTTON_FONT = new Font("黑体", Font.BOLD, 18);

    private ClientService clientService;

    private ClientView clientView;
    // usersListPanel 面板组件
    private JLabel usernameLabel;
    //private JLabel ipAddressLabel;
    DefaultListModel<String> usersListModel;
    JList<String> usersList;
    MyRenderer myRenderer;
    // chatWindowsPanel 面板组件
    JTextArea chatViewTextArea;
    JButton clearButton;
    JTextField chatTextField;
    JButton sendButton;


    public ClientFrame(ClientService clientService) {
        this.clientService = clientService;
        init();
    }

    public void init() {
        this.setTitle("客户端 -- (用户名: " + clientService.username + ")");
        this.setSize(CLIENT_WIDTH, CLIENT_HEIGHT - HEIGHT_CONTROLLER);
        this.setResizable(false);
        this.setLocationRelativeTo(null);

        clientView = new ClientView();
        this.setContentPane(clientView);
        this.addActionListener();

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);

        clientService.clientFrame = this;
        clientService.initClient();
    }

    public void sendMessageAction() {
        if ("".equals(chatTextField.getText())) {
            JOptionPane.showMessageDialog(ClientFrame.this, "发送的消息不能为空", "客户端提醒", JOptionPane.INFORMATION_MESSAGE);
        } else {
            try {
                if ("多人聊天室".equals(clientService.chatObject)) {
                    clientService.sendMessage(MessageProtocol.PUBLIC_ROUND);
                }else {
                    clientService.sendMessage(MessageProtocol.PRIVATE_ROUND);
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    public void addActionListener() {
        clearButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                clientService.chattingRecords.put(clientService.chatObject, "");
                chatViewTextArea.setText("");
            }
        });
        /*sendButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sendMessageAction();
            }
        });*/
        Action sendAction = new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sendMessageAction();
            }
        };
        sendButton.addActionListener(sendAction);
        chatTextField.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "send");
        chatTextField.getActionMap().put("send", sendAction);
        usersList.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                if (e.getValueIsAdjusting()) {
                    clientService.chatObject = usersList.getSelectedValue();
                    myRenderer.removeRowColor(usersList.getSelectedIndex());
                    ClientFrame.this.repaint();
                    chatViewTextArea.setText(clientService.chattingRecords.get(clientService.chatObject));
                }
            }
        });
    }

    class MyRenderer extends DefaultListCellRenderer {

        private ArrayList<Integer> rows;
        private Color rowColor;

        public MyRenderer() {
            rows = new ArrayList<Integer>();
        }

        public void setRowColor(Integer row, Color color) {
            if (!rows.contains(row)) {
                this.rows.add(row);
            }
            this.rowColor = color;
        }

        public void removeRowColor(Integer row) {
            if (rows.contains(row)) {
                this.rows.remove(row);
            }
        }

        @Override
        public Component getListCellRendererComponent(JList list, Object value,
                                                      int index, boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            for (Integer row : rows) {
                if (index == row && !isSelected) {
                    setBackground(this.rowColor);
                }
            }
            return this;
        }
    }

    private class ClientView extends JLayeredPane {

        private JPanel usersListPanel;
        private JPanel chatWindowPanel;

        public ClientView() {
            this.init();
        }

        public void init() {
            this.setBounds(0, 0, CLIENT_WIDTH, CLIENT_HEIGHT - HEIGHT_CONTROLLER);
            this.addElement();
        }

        public void addElement() {
            // 用户信息面板
            usersListPanel = new JPanel(null);
            usersListPanel.setBounds(10, 10, 300, 720 - HEIGHT_CONTROLLER);
            usersListPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.GRAY), "用户列表", TitledBorder.CENTER, TitledBorder.TOP, TEXT_FONT));
            this.add(usersListPanel, 0);
            // 用户名标签
            usernameLabel = new JLabel("用户名: " + clientService.username);
            usernameLabel.setBounds(10, 30, 280, 30);
            usernameLabel.setFont(LABEL_FONT);
            usersListPanel.add(usernameLabel);
            // IP地址标签
            /*ipAddressLabel = new JLabel("IP地址: " + socket.getInetAddress().toString().substring(1) + ":" + socket.getPort());
            ipAddressLabel.setBounds(10, 50, 280, 30);
            ipAddressLabel.setFont(LABEL_FONT);
            usersListPanel.add(ipAddressLabel);*/
            // 用户列表
            usersListModel = new DefaultListModel<String>();
            usersListModel.addElement("多人聊天室");
            usersList = new JList<String>(usersListModel);
            myRenderer = new MyRenderer();
            usersList.setCellRenderer(myRenderer);
            usersList.setFont(new Font("黑体", Font.BOLD, 20));
            usersList.setSelectedIndex(0);
            clientService.chatObject = usersList.getSelectedValue();
            clientService.chattingRecords = new HashMap<String, String>();
            clientService.chattingRecords.put("多人聊天室", "");
            JScrollPane usersListScrollPane = new JScrollPane(usersList);
            usersListScrollPane.setBounds(10, 90, 280, 625 - HEIGHT_CONTROLLER);
            usersListPanel.add(usersListScrollPane);
            // 聊天窗口面板
            chatWindowPanel = new JPanel(null);
            chatWindowPanel.setBounds(320, 10, 650, 720 - HEIGHT_CONTROLLER);
            chatWindowPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.GRAY), "聊天窗口", TitledBorder.CENTER, TitledBorder.TOP, TEXT_FONT));
            this.add(chatWindowPanel, 0);
            // 聊天窗口
            chatViewTextArea = new JTextArea();
            chatViewTextArea.setFont(TEXT_FONT);
            chatViewTextArea.setEditable(false);
            JScrollPane chatViewScrollPane = new JScrollPane(chatViewTextArea);
            chatViewScrollPane.setBounds(10, 20, 630, 650 - HEIGHT_CONTROLLER);
            chatWindowPanel.add(chatViewScrollPane);
            // 清屏按钮
            clearButton = new JButton("清屏");
            clearButton.setBounds(10, 680 - HEIGHT_CONTROLLER, 60, 32);
            clearButton.setFont(BUTTON_FONT);
            clearButton.setBorder(BorderFactory.createRaisedBevelBorder());
            chatWindowPanel.add(clearButton);
            // 消息发送框
            chatTextField = new JTextField();
            chatTextField.setBounds(75, 680 - HEIGHT_CONTROLLER, 500, 32);
            chatTextField.setFont(TEXTFIELD_FONT);
            chatWindowPanel.add(chatTextField);
            // 消息发送按钮
            sendButton = new JButton("发送");
            sendButton.setBounds(580, 680 - HEIGHT_CONTROLLER, 60, 32);
            sendButton.setFont(BUTTON_FONT);
            sendButton.setBorder(BorderFactory.createRaisedBevelBorder());
            chatWindowPanel.add(sendButton);
        }
    }

}